import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '@/utils/store'
import { call } from '@/utils/request'
import { showMsg, showLoading, hideLoading, showSuccess, showBookError } from '@/utils/toast'


Page({
  data: {
    mini_code: null,
    leave_seconds: 0,
    timer_count_down: null,
    pauseTime: 0
  },
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: [
        'config','window_info','user_info'
      ],
    })
  },
  onUnload() {
    // 解绑
    this.storeBindings.destroyStoreBindings()
  },
  onShow() {
    const {pauseTime, leave_seconds} = this.data
    if (pauseTime === 0 || leave_seconds <= 0) return
    const diff = Math.ceil((Date.now() - pauseTime) / 1000)
    this.setData({
      leave_seconds: leave_seconds - diff,
      pauseTime: 0
    })
  },
  onHide() {
    this.setData({ pauseTime: Date.now() })
  },
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.config.contactPhoneNumber
    })
  },
  editUserInfo() {
    if (store.user_info.mobile) {
      wx.navigateTo({
        url: '/pages/edit_user_info/index',
      })
    } else {
      wx.navigateTo({
        url: '/pages/auth_mobile/index',
      })
    }
  },
  getMiniCode() {
    showLoading()
    call('/getMiniCode').then(res => {
      this.setData({
        mini_code: res,
        leave_seconds: 60,
      })
      const timer = setInterval(()=>{
        if (this.data.leave_seconds <= 0) {
          this.setData({
            mini_code: null
          })
          clearInterval(timer)
        } else {
          this.setData({
            leave_seconds: this.data.leave_seconds - 1,
          })
        }
      }, 1000)

      hideLoading()
    })
  }
})
